<?php

/*
 * @Filename     : myTools
 * @Author       : shuang
 * @Email        : shuangbrother@126.com
 * @create_at    : 2014-4-10 17:12:51
 * @Description  : 
 */

namespace common\components;

use Yii;
use yii\helpers\Html;
use yii\helpers\Json;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use common\components\Qiniu;

class MTools {
    /*
     * 权限菜单处理
     * return array
     */

    public static function getAuthMenu() {
        $result = false; //\backend\models\MY_StaticFile::getFileContent(Yii::getAlias('@webroot') . '/chart/statics/menu.php');
        if ($result !== false) {
            $menu = ArrayHelper::toArray(Json::decode($result));
        } else {
            $menu = \backend\models\MY_Mgmt::getMenuData();
        }
        $auth = self::getAdministratorPrivileges();
        foreach ($menu as $key => $sonmenu) {
            foreach (ArrayHelper::getValue($sonmenu, "son") as $item) {
                $flag = false;
                if (!$auth || in_array(strtolower($sonmenu["controller"]) . "-" . strtolower($item["url"]), $auth)) {
                    $flag = true;
                    break;
                }
            }
            if ($flag === false) {
                unset($menu[$key]);
            }
        }
        return ["menu" => $menu, "auth" => $auth];
    }

    /*
     * 邀请码
     */

    public static function makeOnlyNumber() {
        $order_sn = "Y" . substr(time(), -5);
        return $order_sn;
    }

    /*
     * 商品编号
     */

    public static function makeProductNumber() {
        $word = 'D';
        $order_sn = $word . strtoupper(dechex(date('m'))) . date('d') . substr(microtime(), 2, 5) . sprintf('d', rand(0, 99));
        return $order_sn;
    }

    /**
     * @abstract 创建目录
     * @param <type> $dir 目录名
     * @return bool
     */
    public static function createDir($dir) {
        return is_dir($dir) or ( self::createDir(dirname($dir)) and @ mkdir($dir, 0777, true));
    }

    /*
     * @abstract 创建文件
     * @param <type> $file 文件名
     * @return bool
     */

    public static function createFile($file) {
        self::createDir(dirname($file));
        $handle = @fopen($file, "w"); //创建文件
        @fclose($handle);
        return self::isExist($file);
    }

    /*
     * 判断文件是否存在
     * @params {string} $filepath
     * return boolean
     */

    public static function isExist($filepath) {
        return file_exists($filepath);
    }

    /*
     * 读取文件内容
     */

    public static function getFilecontent($path) {
        if (self::isExist($path)) {
            return file_get_contents($path);
        }
        return false;
    }

    /*
     * 设置文件管理根目录
     * @params $string
     * return string
     */

    public static function setfilepath($string = null) {
        $dir = Yii::getAlias('@webroot/') . self::getYiiParams("fileRootDir");
        if (!is_dir($dir)) {
            self::createDir($dir);
        }
        return $dir . $string;
    }

    /*
     * 生成文件全路径名称
     * @params $extension  扩展名
     * @params $flag default false 是否保持原文件名
     * @params $oldfile 原文件名
     * return string
     */

    public static function getfilePath($extension, $flag = false, $oldfile = null) {
        if ($flag === true) {
            return $oldfile . "." . $extension;
        } else {
            $rand = array("a", "b", "c", "d", "e");
            $string = array_rand($rand, 2);
            $dir = "hash/" . $rand[$string[0]] . $rand[$string[1]];
            self::createDir($dir);
            $file = $dir . "/" . time() . '_' . rand(1, 9999) . '.' . $extension;
            return $file;
        }
    }

    /*
     * 删除网站文件
     * @params $filename array 文件名，包含路径
     * return boolen
     */

    public static function deleteFile($filename = array()) {
        if (empty($filename)) {
            return false;
        }
        foreach ($filename as $v) {
            $filepath = self::setfilepath($v);
            if (file_exists($filepath)) {
                $result = unlink($filepath);
                if ($result == false) {
                    return false;
                }
            }
        }
        return true;
    }

    /*
     * 删除网站文件及文件夹
     * @params $dirName  文件夹名
     * @params $auto  可控制是否使用方法生成完整路径
     * return boolen
     */

    public static function deleteDir($dirName = "", $auto = true) {
        if (!$dirName) {
            return false;
        }
        if ($auto == true) {
            $dirName = self::setfilepath($dirName);
        }
        $handle = opendir($dirName);
        while (($file = readdir($handle)) !== false) {
            if ($file != "." && $file != "..") {
                if (is_dir($dirName . "/" . $file)) {
                    deleteDir($dirName . "/" . $file);
                } else {
                    unlink($dirName . "/" . $file);
                }
            }
        }
        closedir($handle);
        if (!rmdir($dirName)) {
            return false;
        }
        return true;
    }

    /*
     * 字典表结构配置
     */

    public static $dictConfigs = [
        "default" => 0,
        "static_http" => 26,
        "static_filetype" => 25,
        "static_dir" => 30,
        "product_wikid" => 40,
        "task_type" => 45,
        "task_single_num" => 51,
        "task_unit_price" => 52,
        "task_status_type" => 66,
        "task_sample_num" => 77
    ];

    /*
     * 列表操作按钮
     * @params $url
     * @params icon
     * @params $tip
     * return string
     */

    public static function getListBtnLink($url, $icon, $tip = "", $options = []) {
        if (!$tip === "") {
            $options["title"] = $tip;
        }
        return Html::a(Html::tag("i", "", ["class" => 'btnicon glyphicon-' . $icon]), $url, $options);
    }

    /*
     * 设置字特殊颜色 0 red 1 green
     * @params $serial
     * @params $string
     */

    public static function setFontColor($serial, $string) {
        if ($serial === null) {
            $serial = 0;
        }
        return '<span class="font-color' . $serial . '">' . $string . '</span>';
    }

    /*
     * 保存数据
     * @params $model
     * return boolean or array
     */

    public static function saveModel($model) {
        if ($model->save()) {
            return true;
        } else {
            return array("errors" => $model->getErrors(), "model" => $model);
        }
    }

    /*
     * 获取选择框常用数据结构  array("value"=>"name");
     * @params $value string
     * @params $name  string
     * return array
     */

    public static function getDropDownListData($data, $default = true, $value = "id", $name = "name", $defaultValue = "全部") {
        $temp = [];
        if ($default) {
            $temp[] = ["id" => -1, "name" => $defaultValue];
        }
        if ($data) {
            foreach ($data as $var) {
                if (is_object($var)) {
                    $temp[] = ["id" => $var->$value, "name" => $var->$name];
                } else if (is_array($var)) {
                    $temp[] = ["id" => $var[$value], "name" => $var[$name]];
                }
            }
        }
        return $temp;
    }

    /*
     * 字典表数据dropdown
     * @params $keyword 关键字键值
     * @params $required default true  
     * return array
     */

    public static function dictDropdown($keyword, $required = false) {
        $resdict = self::Dictdataset();
        if (self::$dictConfigs[$keyword] > 0) {
            $resdict = isset($resdict[self::$dictConfigs[$keyword]]["son"]) ? $resdict[self::$dictConfigs[$keyword]]["son"] : [];
        }
        return self::getDropDownListData($resdict, $required);
    }

    /*
     * 字典表数据dropdown
     * @params $keyword 关键字键值
     * @params $required default true  
     * return array
     */

    public static function dictDropdownDesc($keyword, $required = false, $defaultValue = "--请选择--") {
        $resdict = self::Dictdataset();
        if (self::$dictConfigs[$keyword] > 0) {
            $resdict = isset($resdict[self::$dictConfigs[$keyword]]["son"]) ? $resdict[self::$dictConfigs[$keyword]]["son"] : [];
        }
        return self::getDropDownListData($resdict, $required, "name", "description", $defaultValue);
    }

    /*
     * 获取字典数据集
     */

    public static function Dictdataset() {
        return Json::decode(require Yii::getAlias('@backend') . "/web/chart/statics/dictdataset.php");
    }

    /*
     * 获取但个字典数据项
     * @params $id
     * return array
     */

    public static function getDictdata($id) {
        $data = self::Dictdataset();
        foreach ($data as $item) {
            if ((int) $item["id"] === (int) $id) {
                return $item;
            } else {
                foreach ($item["son"] as $son) {
                    if ((int) $son["id"] === (int) $id) {
                        return $son;
                    }
                }
            }
        }
        return false;
    }

    /*
     * 列表页显示图片
     * @params $path
     * @params $width
     * @params $height
     * return string  
     */

    public static function getPreviewImage($path, $width = 80, $height = 60) {
        return Html::img(self::getYiiParams("website") . "/" . ($path ? $path : self::getYiiParams("admindefaultImage")), ["width" => $width, "height" => $height]);
    }

    /*
     * 前台图片显示路径
     * @parmas $path
     * return string
     */

    public static function getWebPath($path) {
        return self::getYiiParams("website") . "/" . $path;
    }

    /*
     * 系统配置值
     * @params $key
     */

    public static function getYiiParams($attribute) {
        return \yii\helpers\ArrayHelper::getValue(Yii::$app->params, $attribute);
    }

    /*
     * 配置查询的数据列表，管理操作
     * @params type{array} $actions
     * @params $options 其他相关属性
     * return string 
     */

    public static function getStringActions($actions, $options = []) {
        $auth = self::getAdministratorPrivileges();
        $nocheckauth = false;  //判断操作按钮是否显示
        if (!empty($actions)) {
            if (is_array($actions)) {
                $string = "";
                foreach ($actions as $function => $item) {
                    if (ArrayHelper::getValue($options, $function . ".show") !== false) {
                        $firstUrl = ArrayHelper::getValue($options, $function . ".url");
                        if ($firstUrl) {
                            $authUrl = Url::toRoute([$function]);
                            if (!$auth || in_array(strtolower(str_replace("/", "-", substr($authUrl, 1, strpos($authUrl, ".") - 1))), $auth)) {
                                $nocheckauth = true;
                            }
                            $function = $firstUrl;
                        }
                        if ($function === "javascript:;") {
                            $url = $function;
                        } else {
                            if (ArrayHelper::getValue($item, "params")) {
                                array_unshift($item["params"], $function);
                            } else {
                                $item["params"] = [];
                                array_unshift($item["params"], $function);
                            }
                            $url = Url::toRoute($item["params"]);
                        }
                        //判断是否有权限
                        if ($nocheckauth || !$auth || in_array(strtolower(str_replace("/", "-", substr($url, 1, strpos($url, ".") - 1))), $auth)) {
                            if (ArrayHelper::getValue($item, "options")) {
                                $itemoptions = ArrayHelper::merge($item["options"], ["title" => ArrayHelper::getValue($item, "title")]);
                            } else {
                                $itemoptions = ["title" => ArrayHelper::getValue($item, "title")];
                            }
                            if (ArrayHelper::getValue($item, "icon")) {
                                $string .= Html::a(Html::tag("i", "", ["class" => 'btnicon glyphicon-' . $item["icon"]]), $url, $itemoptions);
                            } else {
                                $string .= Html::a(ArrayHelper::getValue($item, "title"), $url, $itemoptions);
                            }
                        }
                    }
                }
                return $string;
            }
        }
        return $actions;
    }

    /*
     * 获取会员权限
     */

    public static function getAdministratorPrivileges() {
        if (self::getYiiParams("auth") === true) {
            return \backend\models\MY_Permission::getAdministratorPrivileges(Yii::$app->user->id);
        }
        return false;
    }

    /*
     * 配置头部菜单
     * return array
     */

    public static $setHeaderMenu = [
        ["title" => "常用工具", "url" => "mgmt/commonlist", "shorttype" => 1, "icon" => "/images/icon04.png"],
        ["title" => "系统设置", "url" => "mgmt/systemlist", "shorttype" => 2, "icon" => "/images/icon06.png"],
    ];

    public static function getTaskPrice($task_price_id) {
        $res = \frontend\models\WB_TaskPrice::findOne($task_price_id);
        if ($res instanceof \frontend\models\WB_TaskPrice) {
            return $res->price;
        }
//        $gradeid = $gradeid ? $gradeid : Yii::$app->user->identity->gradeid;
//        $areaType = Json::decode(self::getTypeGradePrice());
//        $priceType = ArrayHelper::map(ArrayHelper::getValue($areaType, $type . "-" . $gradeid . ".priceData"), "id", "value");
//        return ArrayHelper::getValue($priceType, $task_price_id);
    }

    public static function getTypeGradePrice() {
        return require Yii::getAlias('@backend') . "/web/chart/statics/taskattribute.php";
    }

    /*
     * 七牛云图片上传
     */

    public static function upQiniu($filename, $isbase64 = false) {
        $accessKey = '8g4owxBE3ttWErJ-vtT7kevogpA1CkDkRH4Zjh07';
        $secretKey = 'L_ft0gvXtEqjq0GxoHsor47di2jaogT_DEtDWKhN';
        $bucket = 'heiye';
        // 构建鉴权对象
        $auth = new \Qiniu\Auth($accessKey, $secretKey);
        $token = $auth->uploadToken($bucket);
        $key = time() . mt_rand(0, 999);
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new \Qiniu\Storage\UploadManager();
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        if ($isbase64) {
            list($ret, $err) = $uploadMgr->put($token, $key, $filename);
        } else {
            list($ret, $err) = $uploadMgr->putFile($token, $key, $filename);
        }
        if ($err !== null) {
            return $err;
        } else {
            return $ret["key"];
        }
    }

    /*
     * 整数格式化
     * @params $number
     */

    public static function IntFormat($number) {
        return (int) Yii::$app->formatter->asInteger($number);
    }

    /*
     * 获取七牛图片地址
     */

    public static function getQiniuImagepath($imagehash) {
        if (strpos(self::getYiiParams("imagedomain"), "http://") === 0) {
            return self::getYiiParams("imagedomain") . "/" . $imagehash;
        } else {
            return "http://" . self::getYiiParams("imagedomain") . "/" . $imagehash;
        }
    }

    /*
     * 文件模板
     * @params $filename
     */

    public static function getTemplate($filename) {
        $path = Yii::getAlias('@backend/web/') . self::getYiiParams("fileRootDir") . "template/" . $filename;
        return self::getFilecontent($path);
    }

    /*
     * 获取480图片
     * @params $imagehash
     */

    public static function Qiniu480($imagehash) {
        return self::getQiniuImagepath($imagehash) . "?" . self::getYiiParams("imagedomainWarter480");
    }

    /*
     * 获取640图片
     * @params $imagehash
     */

    public static function Qiniu640($imagehash) {
        return self::getQiniuImagepath($imagehash) . "?" . self::getYiiParams("imagedomainWarter640");
    }

    public static function Qiniunow480($imagehash) {
        return self::getQiniuImagepath($imagehash) . "?" . self::getYiiParams("imagedomainWarter480nowarter");
    }

    /*
     * 打包任务图片
     * @params $taskid
     */

    public static function Qinudown($taskid) {



        $accessKey = '8g4owxBE3ttWErJ-vtT7kevogpA1CkDkRH4Zjh07';
        $secretKey = 'L_ft0gvXtEqjq0GxoHsor47di2jaogT_DEtDWKhN';
        $bucket = 'heiye';

        $auth = new \Qiniu\Auth($accessKey, $secretKey);
        $key = "1479887275";
        // 异步任务的队列， 去后台新建： https://portal.qiniu.com/mps/pipeline
        $pipeline = '';
        $pfop = new \Qiniu\Processing\PersistentFop($auth, $bucket, $pipeline);
        // 进行zip压缩的url
        $url1 = self::Qiniunow480('1479887275');
        $url2 = self::Qiniunow480('1479887334');
        //压缩后的key
        $zipKey = 'test.zip';
        //$download = MTools::getQiniuImagepath($zipKey);
        $fops = 'mkzip/2/url/' . \Qiniu\base64_urlSafeEncode($url1);
        $fops .= '/url/' . \Qiniu\base64_urlSafeEncode($url2);
        $fops .= '|saveas/' . \Qiniu\base64_urlSafeEncode("$bucket:$zipKey");
        list($id, $err) = $pfop->execute($key, $fops);
        echo "\n====> pfop mkzip result: \n";
        if ($err != null) {
            var_dump($err, $id);
            exit;
        } else {
            $ur = $auth->privateDownloadUrl(MTools::getQiniuImagepath($zipKey));
            var_dump($ur);
            exit;
            echo "PersistentFop Id: $id\n";
            $res = "http://api.qiniu.com/status/get/prefop?id=$id";
            echo "Processing result: $res";
            exit;
        }
    }

    /*
     * 任务步骤 多图片
     */

    public static function stepMoreImage($array) {
        $string = "";
        if (is_array($array['tmp_name'])) {
            foreach ($array['tmp_name'] as $item) {
                $string .= self::upQiniu($item) . ",";
            }
            return rtrim($string, ",");
        } else if (is_string($array['tmp_name'])) {
            $string = self::upQiniu($array['tmp_name']);
        }
        return $string;
    }

}
